﻿using System;
using Castle.DynamicProxy;
using OpenQA.Selenium;

namespace Selenium.PageToolkit
{
    public class WebElementInterceptor : IInterceptor
    {
        private readonly Func<ISearchContext> _webDriver;
        private readonly By _spec;
        private object _cache = null;
        public WebElementInterceptor(Func<ISearchContext> webDriver, By spec)
        {
            _webDriver = webDriver;
            _spec = spec;
        }

        public void Intercept(IInvocation invocation)
        {
            if (invocation == null)
            {
                throw new ArgumentNullException("invocation", "invocation cannot be null");
            }
            if (_cache != null)
            {
                invocation.ReturnValue = _cache;
                return;
            }

            if (invocation.Method.Name == "get_LocationOnScreenOnceScrolledIntoView" || invocation.Method.Name == "get_Coordinates")
            {
                invocation.ReturnValue = _cache = invocation.GetConcreteMethod().Invoke(GetElement() as ILocatable, invocation.Arguments);
            }
            else
            {
                invocation.ReturnValue = _cache = invocation.GetConcreteMethod().Invoke(GetElement(), invocation.Arguments);
            }
        }

        private IWebElement GetElement()
        {
            return _webDriver().FindElement(_spec);
        }
    }
}